# -*- coding:utf-8 -*-
import requests
import json
import csv

class TestFood():

    def __init__(self):
        print("start")



    def foodetect(self):
        # 初始化
        food_flag_init = 0
        food_error_init = 0
        food_fail_init = 0
        # 初始化登录接口
        login_url = 'https://api.icarbonx.com/oauth2/token?grant_type=password&sms_verify=true'
        login_header = {"Authorization": "Basic Y29tLm1ldW0uY29hY2guaXBob25lOjdmYTYyZmFmYzgxZTgwMzY="}
        login_data = {
            "username": "15012345678",
            "password": "888888",
            "appName": "health-buddy",
            "grant_type": "password",
            "sms_verify": "true"
        }
        # 登录请求接口
        r_login = requests.post(url=login_url, data=login_data, headers=login_header)

        # 读取csv文件
        with open('E:\\test\\HB\\food_detect_init.csv', 'r') as csvFile:
            reader = csv.reader(csvFile)
            print(type(reader))
            next(reader)
            for row in reader:
                print(row)
                print(type(row))
                print(row[0])
                print(type(row[0]))

                # 食物qa问答接口的请求参数msg
                food_msg = {"msg": row[0]}
                print(food_msg)

                # 获取登录的响应报文
                print(r_login.text)
                login_response = json.loads(r_login.text)
                # 保存登录的token信息
                access_token = login_response['access_token']
                food_headers = {"Authorization": "Bearer " + access_token}
                # qa问答的url
                food_url = 'https://api.icarbonx.com/nlp/api/v1.0/food_detect'
                # qa问答模型接口请求
                r_food = requests.post(url=food_url, data=food_msg, headers=food_headers)
                # 获取响应报文
                print(r_food.text)
                # 转换响应结果为dict格式
                food_response = json.loads(r_food.text)
                print(food_response)
                print(type(food_response))

                # 判断响应结果是否为空,不为空，则获取food和name的名称
                if food_response:
                    print(food_response[0])
                    food_response_all = food_response[0]
                    food_response_all_one = food_response_all['properties']
                    # 获取cal_name的值
                    food_response_cal = food_response_all_one['cal_name']
                    food_response_name = food_response_all_one['name']
                    print("food的calname：" + food_response_cal)
                    #food_response_name
                    if food_response_cal ==  row[0]:
                        # 如果calname和输入的食物名称一致，则测试通过，写入food_py_success文件

                        food_flag_init = food_flag_init + 1
                        print("food匹配成功%d" %food_flag_init)
                    else:
                        fail_data = ['food_name','name','cal_name']
                        food_fail_init = food_fail_init + 1
                        print("food匹配错误%d" %food_fail_init)
                        with open('E:\\test\\HB\\food_detect_fail.csv','a+',encoding='utf-8-sig') as ff:
                            # 先清空文件，再写入新数据
                            # ff.seek(0)
                            # ff.truncate()
                            fail_data[0] = row[0]
                            fail_data[1] = food_response_name
                            fail_data[2] = food_response_cal
                            ff.write(','.join(fail_data))
                            ff.write('\n')
                            ff.close()

                else:
                    food_error_init = food_error_init + 1
                    print("food匹配失败%d" % food_error_init)

                    # 将失败的食物name存在csv文件
                    error_data = ['name']
                    with open('E:\\test\\HB\\food_detect_error.csv','a+',encoding = 'utf-8-sig')as ef:
                        # ef.seek(0)
                        # ef.truncate()
                        error_data[0] = row[0]
                        ef.write(','.join(error_data))
                        ef.write('\n')
                        ef.close()

                    # 如何qa的分值大于闲聊，则返回qa的answer
                data_row = ['food_real_name', 'food_response_name','food_response_cal']
                with open('E:\\test\\HB\\food_detect_py.csv','a+',encoding='utf-8-sig') as f:
                    # csv_write = csv.writer(f)
                    # f.seek(0)
                    # f.truncate()
                    data_row[0] = row[0]
                    data_row[1] = food_response_name
                    data_row[2] = food_response_cal



                        # data_row = list(data_row)
                        # print(data_row)
                    f.write(','.join(data_row))
                    f.write("\n")
                    # f.write("\\n")
                    print("down")
                    f.close()

                    # 打印食物匹配结果
                    print("food匹配成功%d" % food_flag_init)
                    print("food匹配错误%d" % food_fail_init)
                    print("food匹配失败%d" % food_error_init)


        csvFile.close()




if __name__ == '__main__':
    fd = TestFood()
    fd.foodetect()